// 病友圈首页
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Tabs } from 'antd-mobile';
import { SearchOutline } from 'antd-mobile-icons'
import request from '../../api/request';
import VirtualList from '../../components/VirtualList';
import TopHeader from '../../components/TopHeader';
import '../../components/TopHeader.css'
import './index.css';

// ============================
// 类型定义
// ============================
interface Department {
  id: number;
  departmentName: string;
}

interface SickCirclePost {
  sickCircleId: number;
  userId: number;
  title: string;
  detail: string;
  releaseTime: number;
  collectionNum: number;
  commentNum: number;
  amount: number;
}

interface ApiResponse {
  result: Department[];
}

interface SickCircleResponse {
  result: SickCirclePost[];
  message: string;
  status: string;
}

const PAGE_SIZE = 10;

const PatientCircle = () => {
  const navigate = useNavigate();
  // 科室列表与选中科室
  const [departments, setDepartments] = useState<Department[]>([]);
  const [selectedDepartmentId, setSelectedDepartmentId] = useState<number>(1);
  const [loading, setLoading] = useState(false);
  // 病友圈帖子列表
  const [sickCirclePosts, setSickCirclePosts] = useState<SickCirclePost[]>([]);
  const [postsLoading, setPostsLoading] = useState(false);
  // 虚拟列表容器高度（根据窗口尺寸和顶部tabs动态计算）
  const [listHeight, setListHeight] = useState<number>(600);
  // 分页加载状态
  const [page, setPage] = useState<number>(1);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [isFetchingMore, setIsFetchingMore] = useState<boolean>(false);

  // 首次加载：获取科室数据
  useEffect(() => {
    const fetchDepartments = async () => {
      try {
        setLoading(true);
        const res = await request.get('/health/share/knowledgeBase/v1/findDepartment') as ApiResponse;

        if (res.result && Array.isArray(res.result)) {
          setDepartments(res.result);
          // 设置默认选中的科室
          if (res.result.length > 0) {
            setSelectedDepartmentId(res.result[0].id);
          }
        }
      } catch (error) {
        console.error('获取科室数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchDepartments();
  }, []);

  // 计算虚拟列表可视高度（考虑顶部固定tabs与列表外边距）
  useEffect(() => {
    const calculateHeight = () => {
      const tabsEl = document.querySelector('.department-tabs') as HTMLElement | null;
      const tabsHeight = tabsEl ? tabsEl.offsetHeight : 0;
      const listVerticalMargin = 42; // 与 .posts-list 的上下 margin 匹配
      const safetyGap = 8; // 预留一点空隙避免出现滚动条遮挡
      const height = Math.max(300, window.innerHeight - tabsHeight - listVerticalMargin - safetyGap);
      setListHeight(height);
    };

    calculateHeight();
    window.addEventListener('resize', calculateHeight);
    return () => window.removeEventListener('resize', calculateHeight);
  }, []);

  // 选中科室变化时，拉取该科室下的病友圈列表（重置为第一页）
  useEffect(() => {
    if (!selectedDepartmentId) return;

    const fetchSickCirclePosts = async () => {
      try {
        setPostsLoading(true);
        setPage(1);
        setHasMore(true);
        const res = await request.get('/health/user/sickCircle/v1/findSickCircleList', {
          params: {
            departmentId: selectedDepartmentId,
            page: 1,
            count: PAGE_SIZE
          }
        }) as SickCircleResponse;

        if (res.result && Array.isArray(res.result)) {
          setSickCirclePosts(res.result);
          setHasMore(res.result.length === PAGE_SIZE);
        } else {
          setSickCirclePosts([]);
          setHasMore(false);
        }
      } catch (error) {
        console.error('获取病友圈数据失败:', error);
      } finally {
        setPostsLoading(false);
      }
    };

    fetchSickCirclePosts();
  }, [selectedDepartmentId]);

  // 继续加载下一页（触底触发）
  const loadMore = async () => {
    if (isFetchingMore || !hasMore || postsLoading) return;
    try {
      setIsFetchingMore(true);
      const nextPage = page + 1;
      const res = await request.get('/health/user/sickCircle/v1/findSickCircleList', {
        params: {
          departmentId: selectedDepartmentId,
          page: nextPage,
          count: PAGE_SIZE
        }
      }) as SickCircleResponse;

      if (res.result && Array.isArray(res.result) && res.result.length > 0) {
        setSickCirclePosts(prev => [...prev, ...res.result]);
        setPage(nextPage);
        setHasMore(res.result.length === PAGE_SIZE);
      } else {
        setHasMore(false);
      }
    } catch (error) {
      console.error('加载更多数据失败:', error);
    } finally {
      setIsFetchingMore(false);
    }
  };

  const handleDepartmentChange = (key: string) => {
    const departmentId = parseInt(key);
    setSelectedDepartmentId(departmentId);
  };

  // 顶部搜索入口：跳转到搜索页
  const handleSearchClick = () => {
    navigate('/patient-circle/search');
  };

  // 帖子点击：跳转详情
  const handlePostClick = (postId: number) => {
    navigate(`/patient-circle/detail/${postId}`);
  };

  // 格式化时间戳（用于列表显示）
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };

  // 单条帖子渲染
  const renderPostItem = (post: SickCirclePost) => (
    <div
      key={post.sickCircleId}
      className="post-item"
      onClick={() => handlePostClick(post.sickCircleId)}
    >
      {/* 悬赏徽标 - amount>0 显示 */}
      {post.amount > 0 && (
        <div className="reward-badge">
          <span className="reward-icon">H</span>
          <span className="reward-value">{post.amount}</span>
        </div>
      )}
      <div className="post-header">
        <h3 className="post-title">{post.title}</h3>
      </div>
      <div className="post-body">
        <span className="post-time">{formatTime(post.releaseTime)}</span>
        <p className="post-detail">{post.detail}</p>
      </div>
      <div className="post-footer">
        <span className="post-collection">收藏 {post.collectionNum}</span>
        <span className="post-comment">建议 {post.commentNum}</span>
      </div>
    </div>
  );

  return (
    <div className="patient-circle with-top-header">
      <TopHeader hideSearch />
      {/* 科室tabs */}
      <div className="department-tabs">
        {loading ? (
          <div className="loading">加载中...</div>
        ) : (
          <div className="customHeader">
            <Tabs
              activeKey={selectedDepartmentId.toString()}
              onChange={handleDepartmentChange}
              stretch={false}
              autoScroll={false}
              className="tabs"
            >
              {departments.map((department) => (
                <Tabs.Tab
                  title={department.departmentName}
                  key={department.id.toString()}
                >
                </Tabs.Tab>
              ))}
            </Tabs>
            <div style={{
              height: 24,
              width: 1.6,
              background: "#e0e0e0",
              margin: "0 10px",
              display: "inline-block",
            }}
            />
            <SearchOutline className='moreIcon' onClick={handleSearchClick} />
          </div>
        )}
      </div>

      {/* 病友圈内容区域 */}
      <div className="content-area">
        {postsLoading ? (
          <div className="loading">加载中...</div>
        ) : (
          <VirtualList
            className="posts-list"
            data={sickCirclePosts}
            itemHeight={180}
            containerHeight={listHeight}
            onReachEnd={loadMore}
            reachEndOffset={120}
            renderItem={(post) => renderPostItem(post)}
          />
        )}
      </div>
    </div>
  );
};

export default PatientCircle;